package it.polimi.swKnights.SWIMv2.servlets.help;

import it.polimi.swKnights.SWIMv2.ejb.exceptions.InvalidDateException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.InvalidLoginPrivilegesException;
import it.polimi.swKnights.SWIMv2.ejb.exceptions.LoginFailException;
import it.polimi.swKnights.SWIMv2.ejb.helpRequest.HelpRequestHandlerRemote;
import it.polimi.swKnights.SWIMv2.general.Errors;
import it.polimi.swKnights.SWIMv2.servlets.SwimServlet;

import java.io.IOException;

import javax.ejb.EJBException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class HelpRequestProceed
 */
public class HelpRequestProceed extends SwimServlet
{
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{

		HttpSession session = request.getSession();

		String useridHelper = request.getParameter("userid_helper");
		String explanation = request.getParameter("explanation");
		String title = request.getParameter("title");
		String expirationDate = (String) (request.getParameter("date")); //2592000 un mese
		

		String useridAsker = (String) session.getAttribute("userName");
		String password = (String) session.getAttribute("password");
		
		
		if (title == null) 
		{
			title = "";
		}
		
		if (explanation == null || explanation.length() < 20)
		{
			response.sendRedirect("./helpRequest?error=" + Errors.badExplanation);
			return;
		}

		HelpRequestHandlerRemote helpRequestHandler = this
				.lookUp(HelpRequestHandlerRemote.class);

		try
		{
			helpRequestHandler.sendHelpRequest(useridAsker, password,
					useridHelper, title, expirationDate, explanation);
			
			response.sendRedirect("./helpRequest?helpSent=true");
			

		}
		catch (EJBException e)
		{
			response.sendRedirect("./helpRequest?error=" + Errors.notfound);
		}
		catch (LoginFailException e)
		{
			response.sendRedirect("./siteHome?error=" + Errors.session);
		}
		catch (InvalidLoginPrivilegesException e)
		{
			response.sendRedirect("./siteHome?error=" + Errors.session);
		}
		catch (InvalidDateException e)
		{
			response.sendRedirect("./helpRequest?error=" + Errors.dataInPast);
		}

	}

}
